package com.hmys.api.controller;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jsms.api.JSMSClient;
import cn.jsms.api.ValidSMSResult;
import com.github.pagehelper.PageInfo;
import com.hmys.api.config.SMSConfig;
import com.hmys.api.model.WebExpo;
import com.hmys.api.model.WebExpoApply;
import com.hmys.api.model.WebUser;
import com.hmys.api.response.Result;
import com.hmys.api.response.ResultCode;
import com.hmys.api.response.ResultPage;
import com.hmys.api.service.WebExpoApplyService;
import com.hmys.api.service.WebExpoService;
import com.hmys.api.service.WebUserService;
import com.hmys.api.utils.ValidationUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by chen365 on 2018/03/20.
 */
@RestController
@Api(tags = "展会")
@RequestMapping(value = "/expo")
public class ExpoController {

    @Autowired
    private WebExpoService webExpoService;

    @Autowired
    private WebExpoApplyService webExpoApplyService;

    @Autowired
    private WebUserService webUserService;

    @Autowired
    private SMSConfig smsConfig;


    /*
    * 将时间戳转换为时间
    */
    public static String timestampToDate(Long s) {
        if (StringUtils.isEmpty(s)) {
            return null;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(s);
        System.err.println("date:" + date);
        return simpleDateFormat.format(date);
    }

    /**
     * 解析邮编
     *
     * @param postalCode
     * @return
     */
    public static String analysisPostalCode(String postalCode) {
        if (org.apache.commons.lang.StringUtils.isNumeric(postalCode)) {
            if (postalCode.length() != 5) {
                postalCode = null;
            }
        } else {
            if (!org.apache.commons.lang.StringUtils.isEmpty(postalCode)) {
                if (postalCode.length() > 5) {
                    postalCode = postalCode.substring(0, 5);
                } else if (postalCode.length() < 5) {
                    postalCode = null;
                }
                if (!org.apache.commons.lang.StringUtils.isNumeric(postalCode)) {
                    postalCode = null;
                }
            }
        }

        return postalCode;
    }

    public static void main(String[] args) {
        //System.err.println(timestampToDate(953343562392L));
        //String val = "111621";
        //System.err.println(analysisPostalCode(val));
        //System.err.println(val.substring(0, 5));

        String username = "Jennifer Stein";
        String frist_name = username.substring(0, username.lastIndexOf(" "));
        System.err.println(frist_name);
    }

    @ApiOperation(value = "列表", notes = "列表", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Long", name = "type", value = "展会类型（0.所有，1.历届，2.最近）", required = true, paramType = "path"),
            @ApiImplicitParam(dataType = "int", name = "pageIndex", value = "页码", required = true, paramType = "path"),
            @ApiImplicitParam(dataType = "int", name = "pageSize", value = "每页数", required = true, paramType = "path"),
            @ApiImplicitParam(dataType = "Boolean", name = "isRecommend", value = "是否推荐", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Boolean", name = "sort", value = "是否按sort排序", required = false, paramType = "query")
    })
    @GetMapping(value = "/list/{type}/{pageIndex}/{pageSize}")
    public Object list(@PathVariable("type") Integer type,
                       @PathVariable("pageIndex") Integer pageIndex,
                       @PathVariable("pageSize") Integer pageSize, Boolean isRecommend, Boolean sort) {
        WebExpo record = new WebExpo();
        if (!StringUtils.isEmpty(type) && type > 0) {
            record.setType(type);
        }
        if(!StringUtils.isEmpty(isRecommend)){
            record.setIsRecommend(isRecommend);
        }
        record.setStatus(true);
        if(!StringUtils.isEmpty(sort) && sort){
            record.setSort(0);
        }
        PageInfo<WebExpo> pageInfo = webExpoService.selectByBean(pageIndex, pageSize, record);
        if (pageInfo.getList().size() > 0) {
            return new ResultPage(ResultCode.SUCCESS, pageInfo);
        } else {
            return new Result<>(ResultCode.NOT_FOUND);
        }
    }

    @ApiOperation(value = "详情", notes = "详情", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Long", name = "id", value = "新闻ID", required = true, paramType = "path")
    })
    @GetMapping(value = "/detail/{id}")
    public Object detail(@PathVariable("id") Long id) {
        if (!StringUtils.isEmpty(id) && id < 1) {
            return new Result<>(ResultCode.ERROR_PARAM);
        }
        WebExpo record = webExpoService.selectByPrimaryKey(id);
        if (record != null) {
            if (record.getStatus()) {
                return new Result<>(ResultCode.SUCCESS, record);
            } else {
                return new Result<>(ResultCode.HAVE_DELETED);
            }
        } else {
            return new Result<>(ResultCode.NOT_FOUND);
        }
    }

    @ApiOperation(value = "报名", notes = "报名", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "msg", value = "短信", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "msgId", value = "短信ID", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "Long", name = "expoId", value = "展会ID", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "name", value = "姓名", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "phone", value = "手机", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "personnelCount", value = "人数", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "email", value = "邮箱", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "location", value = "所在地", required = true, paramType = "query")
    })
    @PostMapping(value = "/apply")
    public Object apply(String msg, String msgId, Long expoId, String name, String phone,
                        Integer personnelCount, String email, String location) {

        if (!ValidationUtil.isPhone(phone)) {
            return new Result(ResultCode.EMPTY_PHONE);
        }
        if (StringUtils.isEmpty(expoId)) {
            return new Result(ResultCode.EMPTY_EXPO);
        }

        if (StringUtils.isEmpty(personnelCount) || personnelCount < 1) {
            return new Result(ResultCode.EMPTY_EXPO_PERSONNEL_COUNT);
        }

        if (StringUtils.isEmpty(msg)) {
            return new Result(ResultCode.EMPTY_SMS_VALIDATE_CODE);
        }

        if (StringUtils.isEmpty(msgId)) {
            return new Result(ResultCode.EMPTY_MSG_ID);
        }

        if (StringUtils.isEmpty(name)) {
            return new Result(ResultCode.EMPTY_NAME);
        }

        if (StringUtils.isEmpty(email)) {
            return new Result(ResultCode.EMPTY_EMAIL);
        }

        if (!ValidationUtil.isEmail(email)) {
            return new Result(ResultCode.ERROR_EMAIL);
        }

        if (StringUtils.isEmpty(location)) {
            return new Result(ResultCode.EMPTY_LOCATION);
        }

        try {
            JSMSClient jsmsClient = new JSMSClient(smsConfig.getSecret(), smsConfig.getAppkey());
            ValidSMSResult result = jsmsClient.sendValidSMSCode(msgId, msg);
            if (!result.getIsValid()) {
                return new Result(ResultCode.ERROR_VALIDATE_CODE);
            }
        } catch (APIConnectionException e) {
            return new Result(ResultCode.VALIDATE_CODE_FAILED);
        } catch (APIRequestException e) {
            return new Result(ResultCode.VALIDATE_CODE_FAILED);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.ERROR);
        }

        WebExpoApply record = new WebExpoApply();
        record.setExpoId(expoId);
        record.setName(name);
        record.setPhone(phone);
        record.setEmail(email);
        record.setPersonnelCount(personnelCount);
        record.setLocation(location);
        WebUser webUser = webUserService.getCurrentUser();
        if (webUser != null) {
            record.setCreateId(webUser.getUserId());
        }

        if (webExpoApplyService.save(record) > 0) {
            return new Result(ResultCode.SUCCESS);
        } else {
            return new Result(ResultCode.FAIL);
        }
    }


    @ApiOperation(value = "报名", notes = "报名", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "msg", value = "短信", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "msgId", value = "短信ID", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "name", value = "姓名", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "phone", value = "手机", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "county", value = "国家", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "source", value = "来源", required = true, paramType = "query")
    })
    @PostMapping(value = "/apply2")
    public Object apply2(String msg, String msgId, String name, String phone, String county, String source) {

        if (!ValidationUtil.isPhone(phone)) {
            return new Result(ResultCode.EMPTY_PHONE);
        }

        if (StringUtils.isEmpty(msg)) {
            return new Result(ResultCode.EMPTY_SMS_VALIDATE_CODE);
        }

        if (StringUtils.isEmpty(msgId)) {
            return new Result(ResultCode.EMPTY_MSG_ID);
        }

        if (StringUtils.isEmpty(name)) {
            return new Result(ResultCode.EMPTY_NAME);
        }

        if (StringUtils.isEmpty(county)) {
            return new Result(ResultCode.EMPTY_COUNTY);
        }

        if (StringUtils.isEmpty(source)) {
            return new Result(ResultCode.EMPTY_SOURCE);
        }

        try {
            JSMSClient jsmsClient = new JSMSClient(smsConfig.getSecret(), smsConfig.getAppkey());
            ValidSMSResult result = jsmsClient.sendValidSMSCode(msgId, msg);
            if (!result.getIsValid()) {
                return new Result(ResultCode.ERROR_VALIDATE_CODE);
            }
        } catch (APIConnectionException e) {
            return new Result(ResultCode.VALIDATE_CODE_FAILED);
        } catch (APIRequestException e) {
            return new Result(ResultCode.VALIDATE_CODE_FAILED);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.ERROR);
        }

        WebExpoApply record = new WebExpoApply();
        record.setExpoId(0L);
        record.setName(name);
        record.setPhone(phone);
        record.setEmail(null);
        record.setPersonnelCount(null);
        record.setLocation(null);
        record.setCounty(county);
        record.setSource(source);
        WebUser webUser = webUserService.getCurrentUser();
        if (webUser != null) {
            record.setCreateId(webUser.getUserId());
        }

        if (webExpoApplyService.save(record) > 0) {
            return new Result(ResultCode.SUCCESS);
        } else {
            return new Result(ResultCode.FAIL);
        }
    }



    @ApiOperation(value = "渠道报名", notes = "渠道报名", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "msg", value = "短信", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "msgId", value = "短信ID", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "name", value = "姓名", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "phone", value = "手机", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "channel", value = "channel", required = true, paramType = "query")
    })
    @PostMapping(value = "/channel-apply")
    public Object channelApply(String msg, String msgId, String name, String phone, String channel) {

        if (!ValidationUtil.isPhone(phone)) {
            return new Result(ResultCode.EMPTY_PHONE);
        }

        if (StringUtils.isEmpty(msg)) {
            return new Result(ResultCode.EMPTY_SMS_VALIDATE_CODE);
        }

        if (StringUtils.isEmpty(msgId)) {
            return new Result(ResultCode.EMPTY_MSG_ID);
        }

        if (StringUtils.isEmpty(name)) {
            return new Result(ResultCode.EMPTY_NAME);
        }

        if (StringUtils.isEmpty(channel)) {
            return new Result(ResultCode.EMPTY_CHANNEL);
        }

        try {
            JSMSClient jsmsClient = new JSMSClient(smsConfig.getSecret(), smsConfig.getAppkey());
            ValidSMSResult result = jsmsClient.sendValidSMSCode(msgId, msg);
            if (!result.getIsValid()) {
                return new Result(ResultCode.ERROR_VALIDATE_CODE);
            }
        } catch (APIConnectionException e) {
            return new Result(ResultCode.VALIDATE_CODE_FAILED);
        } catch (APIRequestException e) {
            return new Result(ResultCode.VALIDATE_CODE_FAILED);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.ERROR);
        }

        WebExpoApply record = new WebExpoApply();
        record.setExpoId(0L);
        record.setName(name);
        record.setPhone(phone);
        record.setEmail(null);
        record.setPersonnelCount(null);
        record.setLocation(null);
        record.setCounty(null);
        record.setSource("渠道");
        record.setChannel(channel);
        WebUser webUser = webUserService.getCurrentUser();
        if (webUser != null) {
            record.setCreateId(webUser.getUserId());
        }

        if (webExpoApplyService.save(record) > 0) {
            return new Result(ResultCode.SUCCESS);
        } else {
            return new Result(ResultCode.FAIL);
        }
    }

}
